package com.sxy.anli; /**
 * @author 宋鑫宇
 * @version 1.0
 */

import com.sxy.anli.mapper.UserMapper;
import com.sxy.anli.pojo.User;
import com.sxy.anli.util.SqlSessionFactoryUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收传递的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //创建sqlSessionFactory对象,改造创建过程
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        //获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取Mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //验证用户名是否存在
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        User user = mapper.selectByUsername(username);
        if (user != null) {
            //如果已存在则不执行注册语句
            writer.write("用户已存在！");
            sqlSession.close();
            return;
        }
        mapper.add(username, password);
        writer.write("用户注册成功!");

        //提交事务
        sqlSession.commit();
        //关闭资源
        sqlSession.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
